package com.nettyPractice;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import io.netty.util.ReferenceCountUtil;

import java.util.logging.Logger;


/**
 * @author 不鄢
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = Logger.getLogger(NettyClientHandler.class.getName());

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
       try{
           RpcResponse rpcResponse = (RpcResponse) msg;
           logger.info(String.format("客户端接收到消息: %s", rpcResponse));
           // 声明一个AttributeKey对象
           AttributeKey<RpcResponse> key = AttributeKey.valueOf("rpcResponse");
           // 将服务端的返回结果保存到 AttributeMap 上，AttributeMap 可以看作是一个Channel的共享数据源
           // AttributeMap的key是AttributeKey，value是Attribute
           ctx.channel().attr(key).set(rpcResponse);
           ctx.channel().close();
       }finally {
           ReferenceCountUtil.release(msg);
       }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.info("客户端捕获异常" + cause);
        ctx.close();
    }
}
